<?php

namespace App\Services\MakeProductThumbnail;

use App\Models\Product;
use Illuminate\Support\Str;
use Intervention\Image\Gd\Font;
use Illuminate\Support\Facades\File;
use Intervention\Image\Facades\Image;
use Illuminate\Support\Facades\Storage;

class MakeProductThumbnail
{
	/**
	 * @var User
	 */
	protected $user;
	
	/**
	 * @var Product
	 */
	protected $product;
	
	
	public function __construct(Product $product)
	{
		$this->product = $product;
	}

	protected function getPosterName($cover)
	{
		return basename($cover);
	}
	
	protected function getRemotePosterDir($cover)
	{

		$dirname = dirname($cover);
		$dirname = str_replace('https://littleshop.oss-cn-beijing.aliyuncs.com/','',$dirname);
		return $dirname;
	}
	
	protected function getRemotePosterSavePath($cover)
	{
		return $this->getRemotePosterDir($cover) . '/' . $this->getPosterName($cover);
	}
	
	protected function getLocalPosterSavePath(string $name)
	{
		$localPath = public_path('temp/mini-product-thumbnail');
		if (! File::isDirectory($localPath)) {
			File::makeDirectory($localPath, 755, true, true);
		}
		return "{$localPath}/{$name}.jpg";
	}
	
	public function make()
	{
		$product = $this->product;
		
		if (Storage::exists($this->getRemotePosterSavePath($product->cover))) {
			return Storage::url($this->getRemotePosterSavePath($product->cover));
		}
		
		$posterDir = $this->getRemotePosterDir($product->cover);
		$posterName = $this->getPosterName($product->cover);
		

		$cover = Image::make(img_path($product->cover))->resize(194, 194);
		
		Image::canvas(194, 194, '#FFFFFF')
			->insert($cover, 'top', 0, 0)
			->save($this->getLocalPosterSavePath($posterName));
		
		// move to oss.
		Storage::putFileAs($posterDir, $this->getLocalPosterSavePath($posterName), $posterName);
		
		// remove local poster.
		File::delete($this->getLocalPosterSavePath($posterName));
		
		return Storage::url("{$posterDir}/{$posterName}");
	}
}
